import React, { useState, useEffect, useRef } from 'react';
import { withRouter, router } from 'umi';
import { Card, Table, Row, Col, Divider, Tooltip, Popover, Tag, Button } from 'antd';
import Pagination from '@/components/Pagination';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import { toArray, download } from '@/utils/utils';
import useDictionary from '@/hooks/useDictionary';
import { useWorkFlow, useRequest, defaultFormatResult } from '@/hooks';
import IconFont from '@/components/IconFont';

import ControlsItemRestPassword from '@/pages/Organization/EmployeeManage/components/EmployeeCard/components/ControlsItemRestPassword';
import { getFlowByType } from '@/pages/WorkFlow/services';
import authHelper from '@/utils/auth/helper';
import { size } from 'lodash';
import { eventTrack } from '@/utils/track';
import classNames from 'classnames';
import EmployeeListSearch from '../components/EmployeeListSearch';
import WorkTypeCard from '../components/WorkTypeCard';
import SortableModal from '../components/SortableModal';
import { queryEmployeeListPage, downEmployeeList } from '../services';
import styles from './index.less';

const { checkCode } = authHelper;

/**
 * 员工列表
 */
const EmployeeList = ({ location }) => {
    const [sortableModalVisible, setSortableModalVisible] = useState(false);
    const [columns, setColumns] = useState([]);
    const [sexTypeList, getSexTypeText] = useDictionary('sexType'); // 获取性别字典
    const { query = {} } = location;

    const user = JSON.parse(localStorage.getItem('user') || '{}');
    const userRef = useRef(user);

    // 请求数据列表
    const { data = {}, run, loading } = useRequest(params => queryEmployeeListPage(params), {
        manual: true,
        ...defaultFormatResult
    });
    const { total, rows: tableDataSource = [] } = data;

    // 获取离职流程是否存在
    const { run: runFlowByType } = useRequest(() => getFlowByType('quitApply'), {
        manual: true
    });

    // 导出数据
    const { run: runDownLoad, loading: downLoading } = useRequest(params => downEmployeeList(params), {
        manual: true
    });

    const { launch } = useWorkFlow({ launchParam: { type: 'TransferPositionApply' } });
    const { launch: launchDimissionn } = useWorkFlow({ launchParam: { type: 'DimissionProxyApply' } });

    // 监听条件变化拉取数据
    useEffect(() => {
        const {
            pageNo = 1,
            pageSize = 10,
            dutyCodes,
            positionCodes,
            organizationCodes,
            administrativeOrganizationCodes,
            rankCodeList,
            highestDegreeList
        } = query;
        run({
            ...query,
            highestDegreeList: toArray(highestDegreeList),
            organizationCodes: toArray(organizationCodes),
            dutyCodes: toArray(dutyCodes),
            positionCodes: toArray(positionCodes),
            administrativeOrganizationCodes: toArray(administrativeOrganizationCodes),
            rankCodeList: toArray(rankCodeList),
            pageNo,
            pageSize
        });
    }, [query, run]);

    // 替换url
    const handleReplacePage = param => {
        history.push({ query: { ...query, ...param } });
    };

    const handleSearch = e => {
        handleReplacePage({ pageNo: 1, ...e });
    };

    // 分页切换
    const handlePaginationChange = pagination => {
        handleReplacePage({ pageNo: pagination?.current, pageSize: pagination?.pageSize });
    };

    useEffect(() => {
        if (tableDataSource.length > 0) {
            const rouSpanArray = [];
            const computedRowSpan = (record, index) => {
                // 计算 rowSpan
                const firstIndex = tableDataSource.findIndex(item => item.employeeCode === record.employeeCode);
                const count = tableDataSource.filter(item => item.employeeCode === record.employeeCode);
                if (count.length > 1 && !rouSpanArray.includes(record?.employeeCode)) {
                    rouSpanArray.push(count[0]?.employeeCode);
                }

                if (rouSpanArray.includes(record?.employeeCode) && firstIndex !== index) {
                    return 0;
                }
                return count.length || 1;
            };

            const temp = [
                {
                    title: '员工号',
                    dataIndex: 'userNo',
                    key: 'userNo',
                    width: 130,
                    isDisabled: true,
                    isSelected: true,
                    render: (text, record, index) => ({
                        children: text,
                        props: {
                            rowSpan: computedRowSpan(record, index)
                        }
                    })
                },
                {
                    title: '姓名',
                    dataIndex: 'employeeName',
                    key: 'employeeName',
                    isDisabled: true,
                    isSelected: true,
                    width: 150,
                    render: (text, record, index) => {
                        const { employeeCode } = record;
                        return {
                            children: checkCode('office:orgs:employee:detail') ? (
                                <a
                                    className={styles.employeeName}
                                    onClick={async () => {
                                        await eventTrack({
                                            eventName: 'personnel_management_organization_employee_list_name_click',
                                            pageName: 'personnel_management_organization',
                                            eventProps: {
                                                click_context: text
                                            }
                                        });
                                        history.push({
                                            pathname: '/office/personnelManagement/organization/employeeList/detail',
                                            query: { employeeCode }
                                        });
                                    }}
                                >
                                    {text}
                                </a>
                            ) : (
                                <>{text}</>
                            ),
                            props: {
                                rowSpan: computedRowSpan(record, index)
                            }
                        };
                    }
                },
                {
                    title: '性别',
                    dataIndex: 'sex',
                    key: 'sex',
                    width: 120,
                    filteredValue: toArray(query?.sex),
                    filterMultiple: false,
                    filters: sexTypeList,
                    isSelected: true,
                    render: (text, record, index) => ({
                        children: getSexTypeText(text),
                        props: {
                            rowSpan: computedRowSpan(record, index)
                        }
                    })
                },
                {
                    title: '组织机构',
                    dataIndex: 'organizationName',
                    key: 'organizationName',
                    isSelected: true,
                    render: (text, record) => ({
                        children: <Tooltip title={record?.fullOrganizationName}>{text}</Tooltip>,
                        props: {
                            rowSpan: 1
                        }
                    })
                },
                {
                    title: '岗位',
                    dataIndex: 'dutyAlias',
                    key: 'dutyAlias',
                    isSelected: true,
                    render: (text, record) => ({
                        children: (
                            <div style={{ display: 'flex', alignItems: 'center', whiteSpace: 'nowrap' }}>
                                <span className={styles.leaderIconPos}>
                                    {record?.leaderPositionFlag === 1 && record?.leaderShowStatus === 1 && (
                                        <Tooltip arrowPointAtCenter title="审批中">
                                            <IconFont
                                                disabled
                                                icon="iconLeaderMark"
                                                className={styles.employeeLeaderIcon}
                                            />
                                        </Tooltip>
                                    )}
                                    {record?.leaderPositionFlag === 1 && record?.leaderShowStatus !== 1 && (
                                        <IconFont icon="iconLeaderMark" className={styles.employeeLeaderIcon} />
                                    )}
                                </span>
                                {text}
                                {record?.dutyType === 0 ? (
                                    <Tag color="blue" style={{ marginLeft: 8 }}>
                                        兼任
                                    </Tag>
                                ) : (
                                    ''
                                )}
                            </div>
                        ),
                        props: {
                            rowSpan: 1
                        }
                    })
                },
                {
                    title: '职级',
                    dataIndex: 'rankValue',
                    key: 'rankValue',
                    width: 120,
                    isSelected: true,
                    render: (text, record, index) => ({
                        children: <Tooltip title={`${record?.positionName}/${record?.rankValue}`}>{text}</Tooltip>,
                        props: {
                            rowSpan: computedRowSpan(record, index)
                        }
                    })
                },
                {
                    title: '行政机构',
                    dataIndex: 'administrativeOrganizationName',
                    key: 'administrativeOrganizationName',
                    isSelected: true,
                    render: (text, record, index) => ({
                        children: <Tooltip title={record?.fullAdministrativeOrganizationName}>{text}</Tooltip>,
                        props: {
                            rowSpan: computedRowSpan(record, index)
                        }
                    })
                },
                {
                    title: '工作性质',
                    dataIndex: 'workNatureName',
                    key: 'workNatureName',
                    isSelected: true,
                    width: 120,
                    render: (text, record, index) => ({
                        children: text,
                        props: {
                            rowSpan: computedRowSpan(record, index)
                        }
                    })
                },
                {
                    title: '状态',
                    dataIndex: 'serviceStatusName',
                    key: 'serviceStatusName',
                    isSelected: true,
                    width: 120,
                    render: (text, record, index) => ({
                        children: text,
                        props: {
                            rowSpan: computedRowSpan(record, index)
                        }
                    })
                },
                {
                    title: '操作',
                    dataIndex: 'operation',
                    key: 'operation',
                    // align: 'left',
                    // fixed: 'left',
                    width: 154,
                    isSelected: true,
                    render: (text, record, index) => {
                        const { employeeCode, email, employeeName, serviceStatus, dutyCode } = record;

                        return {
                            children: (
                                <div className={styles.operationBtnWrap}>
                                    {checkCode('office:orgs:employee:detail:password') && (
                                        <>
                                            <ControlsItemRestPassword employeeInfo={{ email, employeeName }}>
                                                <Tooltip title="重置密码">
                                                    <IconFont
                                                        isButton
                                                        className={styles.operationBtn}
                                                        icon="iconlistfunction_pwdreset_icon_default"
                                                    />
                                                </Tooltip>
                                            </ControlsItemRestPassword>
                                            <Divider type="vertical" />
                                        </>
                                    )}

                                    {checkCode('office:orgs:employee:care') &&
                                        userRef.current.employeeCode !== employeeCode && (
                                            <>
                                                <Tooltip title="员工关怀">
                                                    <IconFont
                                                        isButton
                                                        className={styles.operationBtn}
                                                        icon="iconlistfunction_employeecare_icon_default"
                                                        onClick={async () => {
                                                            await eventTrack({
                                                                eventName:
                                                                    'personnel_management_organization_employee_list_operator_click',
                                                                pageName: 'personnel_management_organization',
                                                                eventProps: {
                                                                    click_context: `${record.employeeName}-员工关怀`
                                                                }
                                                            });
                                                            history.push({
                                                                pathname:
                                                                    '/office/personnelManagement/organization/employeeList/care',
                                                                query: {
                                                                    employeeCode
                                                                },
                                                                state: { tabRoute: true, tabRefresh: true }
                                                            });
                                                        }}
                                                    />
                                                </Tooltip>
                                                <Divider type="vertical" />
                                            </>
                                        )}
                                    {checkCode('office:orgs:employee:leaderInfo:detail') && (
                                        <>
                                            <Tooltip title="主管信息">
                                                <IconFont
                                                    isButton
                                                    className={styles.operationBtn}
                                                    icon="iconManagerInfosO"
                                                    onClick={async () => {
                                                        await eventTrack({
                                                            eventName:
                                                                'personnel_management_organization_employee_list_operator_click',
                                                            pageName: 'personnel_management_organization',
                                                            eventProps: {
                                                                click_context: `${record.employeeName}-主管信息`
                                                            }
                                                        });
                                                        history.push({
                                                            pathname:
                                                                '/office/personnelManagement/organization/employeeList/supervisor',
                                                            query: {
                                                                employeeCode
                                                            },
                                                            state: { tabRoute: true, tabRefresh: true }
                                                        });
                                                    }}
                                                />
                                            </Tooltip>
                                            <Divider type="vertical" />
                                        </>
                                    )}
                                    <Popover
                                        overlayClassName={styles.operationMoreBtnWrapper}
                                        getPopupContainer={trigger => trigger.parentElement}
                                        placement="topRight"
                                        content={
                                            <ul>
                                                {serviceStatus === 4 && (
                                                    <li>
                                                        <Button
                                                            type="link"
                                                            ghost
                                                            disabled
                                                            onClick={() => {
                                                                eventTrack({
                                                                    eventName:
                                                                        'personnel_management_organization_employee_list_operator_click',
                                                                    pageName: 'personnel_management_organization',
                                                                    eventProps: {
                                                                        click_context: `${record.employeeName}-转正`
                                                                    }
                                                                });
                                                                console.log('employeeCode', employeeCode);
                                                            }}
                                                        >
                                                            <IconFont icon="iconlistfunction_jobtransfer_icon_default" />
                                                            转正
                                                        </Button>
                                                        <Divider />
                                                    </li>
                                                )}

                                                {[1, 4, 5, 9].includes(serviceStatus) && (
                                                    <li>
                                                        <Button
                                                            type="link"
                                                            onClick={() => {
                                                                eventTrack({
                                                                    eventName:
                                                                        'personnel_management_organization_employee_list_operator_click',
                                                                    pageName: 'personnel_management_organization',
                                                                    eventProps: {
                                                                        click_context: `${record.employeeName}-调岗`
                                                                    }
                                                                });
                                                                console.log('employeeCode', employeeCode);
                                                                launch({ employeeCode });
                                                            }}
                                                        >
                                                            <IconFont icon="iconlistfunction_jobswitch_icon_default" />
                                                            调岗
                                                        </Button>
                                                        {serviceStatus !== 5 && <Divider />}
                                                    </li>
                                                )}

                                                {[1, 4, 9].includes(serviceStatus) &&
                                                    checkCode('office:orgs:employee:regisn') && (
                                                        <li>
                                                            <Button
                                                                type="link"
                                                                ghost
                                                                onClick={async () => {
                                                                    await eventTrack({
                                                                        eventName:
                                                                            'personnel_management_organization_employee_list_operator_click',
                                                                        pageName: 'personnel_management_organization',
                                                                        eventProps: {
                                                                            click_context: `${record.employeeName}-离职`
                                                                        }
                                                                    });
                                                                    launchDimissionn({
                                                                        leaverEmployeeCode: employeeCode
                                                                    });
                                                                }}
                                                            >
                                                                <IconFont icon="iconlistfunction_absence_icon_default" />
                                                                离职
                                                            </Button>
                                                        </li>
                                                    )}
                                            </ul>
                                        }
                                        trigger="click"
                                        arrowPointAtCenter
                                    >
                                        <IconFont
                                            disabled={
                                                userRef.current.employeeCode === employeeCode
                                                    ? false
                                                    : !checkCode('office:orgs:employee:more') || size(dutyCode) === 0
                                            }
                                            isButton
                                            className={styles.operationBtn}
                                            icon="iconlistfunction_more_icon_default"
                                        />
                                    </Popover>
                                </div>
                            ),
                            props: {
                                rowSpan: computedRowSpan(record, index)
                            }
                        };
                    }
                }
            ];
            setColumns(temp);
        }
    }, [getSexTypeText, query, runFlowByType, sexTypeList, tableDataSource]);

    // 表格筛选、排序等操作
    const handleTableChange = async (_, filters = {}) => {
        const { sex } = filters;
        if (sex) {
            await eventTrack({
                eventName: 'personnel_management_organization_employee_list_sex_screen_click',
                pageName: 'personnel_management_organization'
            });
        }

        handleReplacePage({
            sex: sex[0]
        });
    };

    React.useEffect(() => {
        eventTrack({
            eventName: 'personnel_management_organization_employeelist_click',
            pageName: 'personnel_management_organization'
        });
    }, []);
    return (
        <PageHeaderWrapper>
            <Card bordered={false}>
                <WorkTypeCard
                    data={{
                        workNature: query?.workNature,
                        dutyType: query?.dutyType,
                        employeeServiceStatus: query?.employeeServiceStatus
                    }}
                    onChange={e => {
                        handleReplacePage({ pageNo: 1, ...e });
                    }}
                />

                <Row type="flex" justify="space-between" align="top">
                    <Col span={22}>
                        <EmployeeListSearch data={query} onSearch={handleSearch} />
                    </Col>
                    <Col span={2} style={{ textAlign: 'right', paddingTop: 5 }}>
                        {checkCode('office:orgs:employee:detail:infoexport') && (
                            <>
                                <Tooltip title="导出">
                                    <IconFont
                                        icon="iconsearchbar_export_icon_default"
                                        disabled={downLoading}
                                        isButton
                                        style={{ fontSize: 20 }}
                                        onClick={async () => {
                                            await eventTrack({
                                                eventName:
                                                    'personnel_management_organization_employee_list_export_click',
                                                pageName: 'personnel_management_organization'
                                            });
                                            const {
                                                organizationCodes,
                                                administrativeOrganizationCodes,
                                                rankCodeList,
                                                highestDegreeList
                                            } = query;
                                            const res = await runDownLoad({
                                                ...query,
                                                highestDegreeList: toArray(highestDegreeList),
                                                organizationCodes: toArray(organizationCodes),
                                                administrativeOrganizationCodes: toArray(
                                                    administrativeOrganizationCodes
                                                ),
                                                rankCodeList: toArray(rankCodeList)
                                            });
                                            download({
                                                getData: () => res
                                            });
                                        }}
                                    />
                                </Tooltip>
                                <Divider type="vertical" style={{ marginTop: '-2px' }} />
                            </>
                        )}

                        <Tooltip title="自定义表头">
                            <IconFont
                                icon="iconsearchbar_modifyheader_icon_default"
                                isButton
                                style={{ fontSize: 20 }}
                                onClick={() => {
                                    setSortableModalVisible(true);
                                    eventTrack({
                                        eventName:
                                            'personnel_management_organization_employee_list_custom_header_click',
                                        pageName: 'personnel_management_organization'
                                    });
                                }}
                            />
                        </Tooltip>
                    </Col>
                </Row>

                {/* 表格 */}
                <Table
                    loading={loading}
                    rowKey="uuid"
                    columns={columns.filter(item => item?.isSelected === true)}
                    dataSource={tableDataSource}
                    pagination={false}
                    onChange={handleTableChange}
                    scroll={{ x: 'max-content' }}
                    style={{
                        marginTop: 24,
                        tableLayout: 'fixed',
                        wordBreak: 'break-word'
                    }}
                    className={classNames(styles.clearHoverChangedBg, styles.employeeList)}
                />

                {/* 分页 */}
                <Pagination
                    current={query?.pageNo}
                    pageSize={query?.pageSize}
                    loading={loading}
                    total={total}
                    onChange={handlePaginationChange}
                />
            </Card>

            <SortableModal
                dataSource={columns}
                visible={sortableModalVisible}
                onCancel={() => {
                    setSortableModalVisible(false);
                }}
                onChange={(selected, alldata) => {
                    setColumns(alldata);
                    setSortableModalVisible(false);
                }}
            />
        </PageHeaderWrapper>
    );
};

export default withRouter(EmployeeList);
